<template>
  <div class="task-detail">
    <div v-if="isLoading">加载中...</div>
    <div v-else-if="!task.id">任务加载失败或不存在。</div>
    <template v-else>
      <h2>任务：{{ task.name }}</h2>
      <el-button @click="goBackToExperiment" type="info" style="margin-bottom: 15px;">返回实验</el-button>
      <el-divider></el-divider>

      <!-- 阅读材料 -->
      <div v-for="material in task.reading_materials" :key="material.id">
        <ReadingMaterialComponent :material="material" />
      </div>

      <!-- 题目组件 -->
      <!-- 单选题 -->
      <div v-for="question in task.single_choice_questions" :key="question.id">
        <SingleChoiceQuestionComponent
          :question="question"
          :answer="singleChoiceAnswers[question.id]"
          @update-answer="(ans) => updateSingleChoiceAnswer(question.id, ans)"
          :disabled="hasSubmitted"
        />
      </div>
      <!-- 多选题 -->
      <div v-for="question in task.multiple_choice_questions" :key="question.id">
        <MultipleChoiceQuestionComponent
          :question="question"
          :answers="multipleChoiceAnswers[question.id] || []"
          @update-answers="(ans) => updateMultipleChoiceAnswer(question.id, ans)"
          :disabled="hasSubmitted"
        />
      </div>
      <!-- 填空题 -->
      <div v-for="question in task.fill_in_blank_questions" :key="question.id">
        <FillInBlankQuestionComponent
          :question="question"
          :answer="fillInBlankAnswers[question.id]"
          @update-answer="(ans) => updateFillInBlankAnswer(question.id, ans)"
          :disabled="hasSubmitted"
        />
      </div>

      <!-- 提交按钮 -->
      <el-button
        type="primary"
        @click="submitAnswers"
        :loading="isSubmitting"
        :disabled="hasSubmitted || Object.keys(allAnswersCombined).length === 0"
        style="margin-top: 20px;"
      >
        {{ hasSubmitted ? '已提交' : '提交答案' }}
      </el-button>

      <!-- 显示评分结果 -->
      <div v-if="scoreInfo" class="score-display">
        <h3>评测结果</h3>
        <p>得分：{{ scoreInfo.total_score }} / {{ scoreInfo.max_score }}</p>
      </div>
    </template>
  </div>
</template>

<script>
import ReadingMaterialComponent from '../components/ReadingMaterialComponent.vue';
import SingleChoiceQuestionComponent from '../components/SingleChoiceQuestionComponent.vue';
import MultipleChoiceQuestionComponent from '../components/MultipleChoiceQuestionComponent.vue';
import FillInBlankQuestionComponent from '../components/FillInBlankQuestionComponent.vue';
import axios from 'axios';

export default {
  name: 'TaskDetailView',
  components: {
    ReadingMaterialComponent,
    SingleChoiceQuestionComponent,
    MultipleChoiceQuestionComponent,
    FillInBlankQuestionComponent
  },
  // Props now include recordId
  props: ['expId', 'taskId', 'recordId'],
  data() {
    return {
      task: {
        name: '',
        reading_materials: [],
        single_choice_questions: [],
        multiple_choice_questions: [],
        fill_in_blank_questions: []
      },
      singleChoiceAnswers: {},
      multipleChoiceAnswers: {},
      fillInBlankAnswers: {},
      scoreInfo: null,
      studentAnswerRecordPK: null, // Will be set from prop/route
      isLoading: true,
      isSubmitting: false,
      hasSubmitted: false, //  Could be derived from record status if backend provides it
    };
  },
  computed: {
    allAnswersCombined() {
      return {
        ...this.singleChoiceAnswers,
        ...this.multipleChoiceAnswers,
        ...this.fillInBlankAnswers,
      };
    }
  },
  async mounted() {
    // Get recordId from route params if not directly passed as prop (depends on router setup)
    this.studentAnswerRecordPK = this.$route.params.recordId || this.recordId;
    if (!this.studentAnswerRecordPK) {
        this.$message.error('答题记录ID缺失，无法加载任务。');
        this.isLoading = false;
        this.task = {}; // Clear task to show error message
        return;
    }
    await this.fetchTaskAndAnswers();
  },
  methods: {
    async fetchTaskAndAnswers() {
      this.isLoading = true;
      try {
        // 1. Fetch Task details (using public API if task structure is public)
        const taskRes = await axios.get(`/api/public/tasks/${this.taskId}/`);
        this.task = taskRes.data;

        // 2. Fetch existing StudentAnswerRecord to populate answers and submission status
        if (this.studentAnswerRecordPK) {
          const recordRes = await axios.get(`/api/student-answers/${this.studentAnswerRecordPK}/`);
          const recordData = recordRes.data;
          this.singleChoiceAnswers = recordData.single_choice_answers || {};
          this.multipleChoiceAnswers = recordData.multiple_choice_answers || {};
          this.fillInBlankAnswers = recordData.fill_in_blank_answers || {};
          
          // Optional: If backend returns score directly on the record after submission
          // you can pre-fill it here. For now, scoreInfo is set after submitAnswers call.
          // Also, you might want a flag on the record like `is_submitted` or `graded_at`
          // to determine `this.hasSubmitted`.
          // For simplicity, if scoreInfo exists, we can assume submitted, but this is not robust.
          // It's better if the backend provides a clear submission status.
          // If the backend's submit_answers response contains the score, we can use that.
          // For now, hasSubmitted will be set true after a successful submission in this session.
        }
      } catch (error) {
        console.error('获取任务或答案失败:', error.response?.data || error.message);
        this.$message.error('加载任务数据失败，请重试。');
        this.task = {}; // Clear task data on error
      } finally {
        this.isLoading = false;
      }
    },
    updateSingleChoiceAnswer(id, answer) {
      if (this.hasSubmitted) return;
      // 直接赋值，Vue 3 会检测到
      this.singleChoiceAnswers[id] = answer;
      console.log('Updated singleChoiceAnswers:', this.singleChoiceAnswers); // 调试用
    },
    updateMultipleChoiceAnswer(id, answers) {
      if (this.hasSubmitted) return;
      // 直接赋值
      this.multipleChoiceAnswers[id] = answers;
      console.log('Updated multipleChoiceAnswers:', this.multipleChoiceAnswers); // 调试用
    },
    updateFillInBlankAnswer(id, answer) {
      if (this.hasSubmitted) return;
      // 直接赋值
      this.fillInBlankAnswers[id] = answer;
      console.log('Updated fillInBlankAnswers:', this.fillInBlankAnswers); // 调试用
    },
    async submitAnswers() {
      if (this.isSubmitting || this.hasSubmitted) {
        this.$message.warning(this.hasSubmitted ? '您已提交过答案！' : '正在提交中，请稍候...');
        return;
      }
      if (Object.keys(this.allAnswersCombined).length === 0) {
        this.$message.warning('请至少回答一道题目后再提交。');
        return;
      }

      this.isSubmitting = true;

      const payload = {
        // No task_id here, as it's tied to the StudentAnswerRecord PK
        answers: {
          single_choice: this.singleChoiceAnswers,
          multiple_choice: this.multipleChoiceAnswers,
          fill_in_blank: this.fillInBlankAnswers
        }
      };

      try {
        const response = await axios.post(
          `/api/student-answers/${this.studentAnswerRecordPK}/submit_answers/`,
          payload
        );

        if (response.data && response.data.score) {
          this.scoreInfo = response.data.score;
          this.$message.success('答案已提交，评测完成！');
          this.hasSubmitted = true;
        } else {
          this.$message.error('提交成功，但未能获取评分结果。');
          console.error('Unexpected response structure for score:', response.data);
        }
      } catch (error) {
        console.error('提交失败:', error.response || error);
        let errMsg = '提交失败，请重试';
        if (error.response && error.response.data) {
          if (error.response.data.detail) errMsg = error.response.data.detail;
          else if (typeof error.response.data === 'string') errMsg = error.response.data;
          else if (error.response.data.error) errMsg = error.response.data.error;
        }
        this.$message.error(errMsg);
      } finally {
        this.isSubmitting = false;
      }
    },
    // getStudentAnswerRecordId() method is no longer needed here
    // as studentAnswerRecordPK is directly available.

    // The local evaluateAnswers is no longer needed if backend handles scoring.
    // If you keep it for immediate feedback before backend confirmation, that's fine,
    // but the authoritative score should come from the backend.

    goBackToExperiment() {
      this.$router.push(`/experiments/${this.expId}`);
    }
  }
};
</script>

<style scoped>
.task-detail {
  padding: 20px;
}
.score-display {
  margin-top: 20px;
  padding: 15px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  background-color: #f9f9f9;
}
.score-display h3 {
    margin-top: 0;
}
</style>